/**
 * @Author: langchenglai
 * @Date:   2018-04-20 09:24:52
 * @Email:  lclangcheng@gmail.com
 * @Filename: elasticsearch.js
 * @Last modified by:   lclangcheng
 * @Last modified time: 2018-07-16 13:53:49
 * @License: jin10
 * @Copyright: jin10
 */
'use strict'

const config = require('config')
const elasticsearch = require('elasticsearch')
const AgentKeepAlive = require('agentkeepalive')

const esClient = new elasticsearch.Client({
  hosts: [
    {
      host: config.es.master.host,
      port: config.es.master.port,
      apiVersion: config.es.master.apiVersion,
      log: config.es.master.log,
      auth: config.es.master.httpAuth,
      weight: config.es.master.weight,
      createNodeAgent: function (connection, config) {
        // https://github.com/elastic/elasticsearch-js/issues/196
        return new AgentKeepAlive(connection.makeAgentConfig(config))
      }
    }
  ],
  selector: function (nodes) {
    nodes = nodes.sort((_a, _b) => { return _b.host.weight - _a.host.weight })
    return nodes[0]
  }
})

module.exports = esClient
